package com.whq.common.mail;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

/**
 * 
 * 发送简单邮件
 * 
 * @author wanghuaiqiang 2008-11-14
 * 
 */
public class SendMail {
	/**
	 * 保存附件
	 * 
	 * @param allMultiPart
	 * @param mailModel
	 * @throws MessagingException
	 */
	private static void createAttachPart(MimeMultipart allMultiPart,
			MailModel mailModel) throws MessagingException {
		for (int i = 0; i < mailModel.getAttachList().size(); i++) {
			MimeBodyPart attachPart = new MimeBodyPart();
			DataHandler dh = new DataHandler(new ByteArrayDataSource(
					(byte[]) mailModel.getAttachList().get(i),
					"application/octet-stream"));
			attachPart.setDataHandler(dh);
			attachPart.setFileName(new Integer(i).toString() + ".png");
			allMultiPart.addBodyPart(attachPart);
		}
	}

	/**
	 * 新建一个存放信件内容的BodyPart对象
	 * 
	 * @param mailModel
	 * @return
	 * @throws Exception
	 */
	private static MimeBodyPart createContent(MailModel mailModel)
			throws Exception {
		MimeBodyPart contentPart = new MimeBodyPart();
		MimeMultipart contentMultiPart = new MimeMultipart("related");

		// 保存HTML正文
		MimeBodyPart htmlBodyPart = new MimeBodyPart();
		htmlBodyPart.setContent(mailModel.getContent(), mailModel.getContentType());
		contentMultiPart.addBodyPart(htmlBodyPart);

		// 保存图片的MimeBodyPart
		for (int i = 0; i < mailModel.getAttachList().size(); i++) {
			MimeBodyPart pngBodyPart = new MimeBodyPart();
			DataHandler dh = new DataHandler(new ByteArrayDataSource(
					(byte[]) mailModel.getAttachList().get(i),
					"application/octet-stream"));
			pngBodyPart.setDataHandler(dh);
			pngBodyPart.setContentID("IMG" + new Integer(i).toString());
			// pngBodyPart.setHeader("Content-ID", "IMG" + new
			// Integer(i).toString());
			contentMultiPart.addBodyPart(pngBodyPart);
		}

		contentPart.setContent(contentMultiPart);
		return contentPart;
	}
	
	/**
	 * 发送邮件
	 * @param mailModel
	 * @throws Exception
	 */
	public static void send(MailModel mailModel) throws Exception {
		// 发件人使用发邮件的电子信箱服务器
		String host = mailModel.getSmtpServer();
		// 发邮件的目的地（收件人信箱）
		String toMailList[] = mailModel.getToMailList();
		Address[] toAddresses = new InternetAddress[toMailList.length];
		for (int i = 0; i < toMailList.length; i++) {
			toAddresses[i] = new InternetAddress(toMailList[i]);
		}

		// Get system properties
		Properties props = System.getProperties();

		// Setup mail server
		props.put("mail.smtp.host", host);

		// Get session
		props.put("mail.smtp.auth", "true"); // 这样才能通过验证

		MyAuthenticator myauth = new MyAuthenticator(mailModel
				.getAuthUsername(), mailModel.getAuthPassword());
		Session session = Session.getDefaultInstance(props, myauth);

		// session.setDebug(true);
		// Define message
		MimeMessage message = new MimeMessage(session);

		// Set the from address
//		String fromName = new String(mailModel.getFromName().getBytes(), "utf-8"); 
		message.setFrom(new InternetAddress(mailModel.getFrom(), mailModel.getFromName()));

		// Set the to address
		message.addRecipients(Message.RecipientType.TO, toAddresses);

		// Set the subject
		message.setSubject(mailModel.getSubject());
		
		// Set the send date
		message.setSentDate(new Date());
		
		// 发送文本邮件
		if (mailModel.getMailType().equals(MailModel.MAIL_TYPE_TEXT)) {
			// Set the content
			message.setText(mailModel.getContent());

			message.saveChanges();
			Transport.send(message);
		} 
		// 发送 HTML 邮件
		else {
			// 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
			MimeMultipart allMultiPart = new MimeMultipart("mixed");

			// 新建一个存放信件内容的BodyPart对象
			MimeBodyPart contentPart = createContent(mailModel);
			allMultiPart.addBodyPart(contentPart);

			// 保存附件
			createAttachPart(allMultiPart, mailModel);

			message.setContent(allMultiPart);
			message.saveChanges();

			javax.mail.Transport transport = session.getTransport("smtp");
			transport.connect();
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		}
	}
	
	/**
	 * 通过SSL发送邮件
	 * @param mailModel
	 * @throws Exception
	 */
	public static void sendViaSsl(MailModel mailModel) throws Exception {
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		
		// 发邮件的目的地（收件人信箱）
		String toMailList[] = mailModel.getToMailList();
		Address[] toAddresses = new InternetAddress[toMailList.length];
		for (int i = 0; i < toMailList.length; i++) {
			toAddresses[i] = new InternetAddress(toMailList[i]);
		}

		// Get system properties
		Properties props = System.getProperties();
		
		// 发件人使用发邮件的电子信箱服务器
		props.setProperty("mail.smtp.host", mailModel.getSmtpServer());
		
		props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
		
		props.setProperty("mail.smtp.socketFactory.fallback", "false");

		// 邮件服务器端口号
		props.setProperty("mail.smtp.port", mailModel.getSmtpPort().toString());
		
		props.setProperty("mail.smtp.socketFactory.port", mailModel.getSmtpPort().toString());

		// Get session
		props.put("mail.smtp.auth", "true"); // 这样才能通过验证

		final String username = mailModel.getAuthUsername();
		final String password = mailModel.getAuthPassword();
		
		Session session = Session.getDefaultInstance(props,
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		// session.setDebug(true);
		// Define message
		MimeMessage message = new MimeMessage(session);

		//发邮件的出发地（发件人的信箱）
//		String fromName = new String(mailModel.getFromName().getBytes(), "utf-8"); 
		message.setFrom(new InternetAddress(mailModel.getFrom(), mailModel.getFromName()));

		// Set the to address
		message.addRecipients(Message.RecipientType.TO, toAddresses);

		// Set the subject
		message.setSubject(mailModel.getSubject());
		
		// Set the send date
		message.setSentDate(new Date());

		// 发送文本邮件
		if (mailModel.getMailType().equals(MailModel.MAIL_TYPE_TEXT)) {
			// Set the content
			message.setText(mailModel.getContent());
			
			message.setSentDate(new Date());

			message.saveChanges();
			Transport.send(message);
		}
		// 发送 HTML 邮件
		else {
			// 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
			MimeMultipart allMultiPart = new MimeMultipart("mixed");

			// 新建一个存放信件内容的BodyPart对象
			MimeBodyPart contentPart = createContent(mailModel);
			allMultiPart.addBodyPart(contentPart);

			// 保存附件
			createAttachPart(allMultiPart, mailModel);

			message.setContent(allMultiPart);
			message.saveChanges();

			javax.mail.Transport transport = session.getTransport("smtp");
			transport.connect();
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		}
	}
}